/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.proposeproduct.web.ProposeProductUploadImgAction
   Module Description   :

   Date Created      : 2009/12/9
   Original Author   : ellen.li
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.proposeproduct.web;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.utils.ImageUtils;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.image.entity.Image;
import com.yaodian100.ec.image.entity.Image.IMG_TYPE;
import com.yaodian100.ec.image.service.Image2Service;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.SpecificationMajor;
import com.yaodian100.ec.product.service.Product2Service;
import com.yaodian100.ec.proposeproduct.entity.ProposeProduct;
import com.yaodian100.ec.proposeproduct.entity.ProposeSpecification;
import com.yaodian100.ec.proposeproduct.service.ProposeProductService;
import com.yaodian100.ec.proposeproduct.service.ProposeSpecificationService;

/**
 * @author ellen.li
 * 
 */
public class ProposeProductUploadImgAction extends ActionSupport implements Preparable {

	/**
	 * serial version
	 */
	private static final long serialVersionUID = 5136793753493571924L;

	private static void copyStreams(InputStream input, OutputStream output) throws IOException {
		int count;
		byte data[] = new byte[1024];
		while ((count = input.read(data, 0, 1024)) != -1) {
			output.write(data, 0, count);
		}
	}

	public static void unzip(File srcFile, File destDir) throws IOException {
		InputStream input = null;
		OutputStream output = null;
		ZipFile zipfile = new ZipFile(srcFile);
		Enumeration zipEntries = zipfile.entries();
		while (zipEntries.hasMoreElements()) {
			ZipEntry entry = (ZipEntry) zipEntries.nextElement();
			if (entry.isDirectory()) {
				new File(destDir, entry.getName()).mkdir();
				continue;
			}
			input = new BufferedInputStream(zipfile.getInputStream(entry));
			File destFile = new File(destDir, entry.getName());
			FileOutputStream fos = new FileOutputStream(destFile);
			output = new BufferedOutputStream(fos);
			copyStreams(input, output);
			input.close();
			output.flush();
			output.close();
		}
	}

	private final Logger logger = LoggerFactory.getLogger(ProposeProductUploadImgAction.class);
	private ProposeProductService proposeProductService;
	private ProposeProduct proposeProduct;
	@Resource
	private Image2Service image2Service;
	@Resource
	private Product2Service product2Service;
	@Resource
	private ProposeSpecificationService proposeSpecificationService;

	private CommonCriteria crit;
	private File[] upload;
	private String[] uploadFileName;// 设置上传文件的文件名
	private StringBuffer imgMfilePath;
	private String brief;
	private String description;
	private String details;
	private List<ProposeProduct> proposeProducts;
	private Image image;
	private String prpsPrdctBatchId;
	private String enterPrdctBatchId;
	private String flag;
	private String subName;

	public String getBrief() {
		return brief;
	}

	public String getDescription() {
		return description;
	}

	public String getDetails() {
		return details;
	}

	/**
	 * @return the enterPrdctBatchId
	 */
	public String getEnterPrdctBatchId() {
		return enterPrdctBatchId;
	}

	/**
	 * @return the flag
	 */
	public String getFlag() {
		return flag;
	}

	/**
	 * @return the image
	 */
	public Image getImage() {
		return image;
	}

	/**
	 * @return the imageService
	 */
	// public Image2Service getImageService() {
	// return imageService;
	// }

	public StringBuffer getImgMfilePath() {
		return imgMfilePath;
	}

	/**
	 * @return the proposeProduct
	 */
	public ProposeProduct getProposeProduct() {
		return proposeProduct;
	}

	/**
	 * @return the proposeProducts
	 */
	public List<ProposeProduct> getProposeProducts() {
		return proposeProducts;
	}

	/**
	 * @return the proposeProductService
	 */
	public ProposeProductService getProposeProductService() {

		return proposeProductService;
	}

	/**
	 * @return the prpsPrdctBatchId
	 */
	public String getPrpsPrdctBatchId() {
		return prpsPrdctBatchId;
	}

	/**
	 * @return the upload
	 */
	public File[] getUpload() {
		return upload;
	}

	/**
	 * @return the uploadFileName
	 */
	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void prepare() throws Exception {

	}

	/* 處理上傳商品圖 */
	public String processUploadImg() {
		try {
			StringBuffer sbMainPath = new StringBuffer();
			imgMfilePath = new StringBuffer();
			imgMfilePath.append(ServerValue.getMidApachePath()).append(File.separator).append("PImg").append(File.separator);
			crit = new CommonCriteria();
			if (StringUtils.isNotBlank(prpsPrdctBatchId)) {
				crit.addEq("proposeProductBatchId", prpsPrdctBatchId);
			} else if (StringUtils.isNotBlank(enterPrdctBatchId)) {
				crit.addEq("proposeProductBatchId", enterPrdctBatchId);
			}
			proposeProducts = proposeProductService.getList(0, -1, crit, null);

			StringBuilder sbNameMapKey = new StringBuilder();
			StringBuilder sbNameMapValue = new StringBuilder();
			// 處理zip檔
			ImageUtils imageUtils = new ImageUtils();
			String timeflag2 = String.valueOf(new Date().getTime());
			File tmpZipDir = new File(imgMfilePath.toString() + "tmpZip" + timeflag2);
			FileUtils.forceMkdir(tmpZipDir);
			for (int i = 0; i < upload.length; i++) {
				if (uploadFileName[i].endsWith("zip") == true) {// 判斷上傳檔案是否為zip檔
					// 先解壓至tmpZip目錄下
					unzip(upload[i], tmpZipDir);
				}
			}
			File[] fileslist = FileUtils.convertFileCollectionToFileArray(FileUtils.listFiles(tmpZipDir, null, false));
			Map<String, String> descMap = new HashMap<String, String>();
			// Map<String, String> mainMap = new HashMap<String, String>();
			Map<String, String> prdtMap = new HashMap<String, String>();
			// FileInputStream fis;
			Map<String, String> replaceNameMap = new HashMap<String, String>();
			List<String> replaceMapKeyList = new ArrayList<String>();
			for (ProposeProduct aProposeProduct : proposeProducts) {// 找出此批號的所有提報商品
				descMap.clear();
				prdtMap.clear();
				Product product = product2Service.get(aProposeProduct.getId());
				// boolean hasCover = false;

				List<SpecificationMajor> specMajors = null;
				if (null != product) {
					specMajors = product.getSpecMajors();
				}

				String baseImgPath = "/PImg/" + aProposeProduct.getId().substring(0, 4) + "/" + aProposeProduct.getId() + "/"
						+ aProposeProduct.getId();
				String[] descImgArray = {};
				// 處理說明圖檔
				if (null != aProposeProduct.getProposeProductDescImg()) {
					descImgArray = aProposeProduct.getProposeProductDescImg().split(",");
					int iDescImaArray = descImgArray.length;
					for (int i = 0; i < iDescImaArray; i++) {
						descMap.put(descImgArray[i].trim().toLowerCase(), aProposeProduct.getId());// 先將商品提報檔的說明圖檔名及ID裏放入Map
					}
				}
				// 處理說商品圖檔
				if (null != aProposeProduct.getProposeProductPrdtImg()) {
					String[] prdtImgArray = aProposeProduct.getProposeProductPrdtImg().split(",");
					int iPrdtImaArray = prdtImgArray.length;
					for (int i = 0; i < iPrdtImaArray; i++) {
						prdtMap.put(prdtImgArray[i].trim().toLowerCase(), aProposeProduct.getId());// 先將商品提報檔的商品圖檔名及ID裏放入Map
					}
				}
				for (int i = 0; i < upload.length; i++) {
					if (uploadFileName[i].endsWith("zip") == true) {// 判斷上傳檔案是否為zip檔
						for (int ii = 0; ii < fileslist.length; ii++) {

							/* 開始存說明檔圖片 */
							if (descMap.containsKey(fileslist[ii].getName().toLowerCase())) {// 判斷上傳的圖檔是否包含在Map裏
								if (descMap.get(fileslist[ii].getName().toLowerCase()).equals(aProposeProduct.getId())) {// 只有相同的ID才存入路徑及圖檔
									File[] descFileList = { fileslist[ii] };
									// fis = new FileInputStream(fileslist[ii]);
									// File f = new File(imgMfilePath.toString() + fileslist[ii].getName());
									// InputStream inputStream = new FileInputStream(fileslist[ii]);
									// OutputStream out = new FileOutputStream(f);
									// byte buf[] = new byte[1024];
									// int len;
									// while ((len = inputStream.read(buf)) > 0) {
									// out.write(buf, 0, len);
									// }
									// out.close();
									// inputStream.close();
									// BufferedImage bufferedImage = ImageIO
									// .read(new File(imgMfilePath.toString() + fileslist[ii].getName()));
									// imageUtils = new ImageUtils();
									// String timeflag = String.valueOf(new Date().getTime());
									// if (fileslist[ii].getName().toLowerCase().endsWith("jpg") == true) {
									// subName = "jpg";
									// imageUtils.descResize(aProposeProduct.getId(), bufferedImage, "d" + timeflag, subName, imgMfilePath
									// .toString());
									// }
									// if (fileslist[ii].getName().toLowerCase().endsWith("gif") == true) {
									// subName = "gif";
									// imageUtils.descResize(aProposeProduct.getId(), bufferedImage, "d" + timeflag, subName, imgMfilePath
									// .toString());
									// }
									// image = new Image();
									// image.setImgFilePath(baseImgPath + "_d" + timeflag + "." + "jpg");
									// image.setProductId(aProposeProduct.getId());
									// image.setShowSeq(ii + 1);
									// image.setType(IMG_TYPE.DESC.getValue());
									// image.setIsDelete("N");
									// imageService.save(image);
									//
									// // 将值放入map及list ex:key=newname.jpg value=oldname.jpg,0001
									// sbNameMapKey.setLength(0);
									// sbNameMapValue.setLength(0);
									// sbNameMapKey.append(aProposeProduct.getId()).append("_d").append(timeflag).append(".")
									// .append(subName);
									// sbNameMapValue.append(fileslist[ii].getName()).append(",").append(aProposeProduct.getId());
									// replaceNameMap.put(sbNameMapKey.toString(), sbNameMapValue.toString());
									// replaceMapKeyList.add(sbNameMapKey.toString());
									BufferedImage bufferedImage = ImageIO.read(fileslist[ii]);
									if (bufferedImage.getWidth() <= 700) {
										image2Service.uploadImage(aProposeProduct.getId(), new ArrayList<String>(Arrays
												.asList(IMG_TYPE.DESC.getValue())), null, new ArrayList<File>(Arrays.asList(descFileList)),
												null);
									} else {
										this.addActionError("商品 " + aProposeProduct.getId() + "，说明图片:" + fileslist[ii].getName()
												+ "宽度限700以内");
									}
								}
							}
							/* 開始存商品圖片 */
							if (prdtMap.containsKey(fileslist[ii].getName().toLowerCase())) {// 判斷上傳的圖檔是否包含在Map裏
								if (prdtMap.get(fileslist[ii].getName().toLowerCase()).equals(aProposeProduct.getId())) {// 只有相同的ID才存入路徑及圖檔
									File[] prdtFileList = { fileslist[ii] };
									BufferedImage bufferedImage = ImageIO.read(fileslist[ii]);
									if (bufferedImage.getWidth() == 520 && bufferedImage.getHeight() <= 620) {

										image2Service.uploadImage(aProposeProduct.getId(), new ArrayList<String>(Arrays
												.asList(IMG_TYPE.PRDT.getValue())), null, new ArrayList<File>(Arrays.asList(prdtFileList)),
												null);
									} else {
										this.addActionError("商品 " + aProposeProduct.getId() + "`,商品图片:" + fileslist[ii].getName()
												+ "尺寸应为520x620");
									}

								}
							}

							// 需要主規格id的圖：主規格方形圖，主規格長形圖，方形規格細節圖，長形規格細節圖，主規格示意圖
							if (null != specMajors) {
								for (SpecificationMajor specMajor : specMajors) {
									List<ProposeSpecification> pss = proposeSpecificationService.getSpecificationByProductIdAndMainName(
											product.getProductId(), specMajor.getMainSpecName());

									if (pss.size() > 0) {
										ProposeSpecification ps = pss.get(0);
										String coverId = "";
										if ("Y".equals(ps.getIsCover())) {
											coverId = specMajor.getMainSpecId().toString();

										}
										String tmpMianImg = fileslist[ii].getName();
										// 主規格方形圖
										if (null != ps.getProposeProductMainImg()) {
											if (ps.getProposeProductMainImg().toLowerCase().equals(tmpMianImg.toLowerCase())) {

												BufferedImage bufferedImage = ImageIO.read(fileslist[ii]);
												if (bufferedImage.getWidth() == 500 && bufferedImage.getHeight() == 500) {
													File[] mainFileList = { fileslist[ii] };
													// 上傳主檔圖片
													image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
															.asList(IMG_TYPE.MAIN.getValue())), new ArrayList<String>(Arrays.asList(specMajor
															.getMainSpecId().toString())), new ArrayList<File>(Arrays.asList(mainFileList)), null,
															coverId);

													// 將原始主圖檔存一份起來
													sbMainPath.setLength(0);
													sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
													sbMainPath.append(aProposeProduct.getId().substring(0, 4));
													sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
															.append(tmpMianImg);
												} else {
													this.addActionError("商品 " + aProposeProduct.getId() + "，主规格方形图:" + fileslist[ii].getName()
															+ "尺寸应为500x500");
												}
											}
										}
										// 主規格長形圖
										if (null != ps.getProposeProductRMainImg()) {
											if (ps.getProposeProductRMainImg().toLowerCase().equals(tmpMianImg.toLowerCase())) {

												BufferedImage bufferedImage = ImageIO.read(fileslist[ii]);
												if (bufferedImage.getWidth() == 400 && bufferedImage.getHeight() == 530) {
													File[] rmainFileList = { fileslist[ii] };

													// 上傳主檔圖片
													image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
															.asList(IMG_TYPE.RMAIN.getValue())), new ArrayList<String>(Arrays.asList(specMajor
															.getMainSpecId().toString())), new ArrayList<File>(Arrays.asList(rmainFileList)), null);

													// 將原始主圖檔存一份起來
													sbMainPath.setLength(0);
													sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
													sbMainPath.append(aProposeProduct.getId().substring(0, 4));
													sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
															.append(tmpMianImg);
												} else {
													this.addActionError("商品 " + aProposeProduct.getId() + "，主规格长型图:" + fileslist[ii].getName()
															+ "尺寸应为400x530");
												}
											}
										}

										// 規格細節圖，圖檔類型由"商品页为长形图/正方图?"來決定
										String mainPicType = "S".equals(aProposeProduct.getGraphicType()) ? IMG_TYPE.MAIN.getValue()
												: IMG_TYPE.RMAIN.getValue();
										if (null != ps.getProposeProductMainSpecPic()) {
											if (ps.getProposeProductMainSpecPic().toLowerCase().equals(tmpMianImg.toLowerCase())) {
												BufferedImage bufferedImage = ImageIO.read(fileslist[ii]);
												if (("S".equals(aProposeProduct.getGraphicType()) && bufferedImage.getWidth() == 400 && bufferedImage
														.getHeight() == 400)
														|| ("R".equals(aProposeProduct.getGraphicType()) && bufferedImage.getWidth() == 400 && bufferedImage
																.getHeight() == 530)) {
													File[] mainFileList = { fileslist[ii] };
													// 上傳主檔圖片
													image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
															.asList(mainPicType)), new ArrayList<String>(Arrays.asList(specMajor.getMainSpecId()
															.toString())), new ArrayList<File>(Arrays.asList(mainFileList)), null);

													// 將原始主圖檔存一份起來
													sbMainPath.setLength(0);
													sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
													sbMainPath.append(aProposeProduct.getId().substring(0, 4));
													sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
															.append(tmpMianImg);
												} else {
													this.addActionError("商品 " + aProposeProduct.getId() + "，规格细节图:" + fileslist[ii].getName()
															+ "尺寸相同于主图尺寸");
												}
											}
										}

										// 主規格示意圖
										if (null != ps.getProposeProductIconPic()) {
											if (ps.getProposeProductIconPic().toLowerCase().equals(tmpMianImg.toLowerCase())) {
												BufferedImage bufferedImage = ImageIO.read(fileslist[ii]);
												if (bufferedImage.getWidth() == 40 && bufferedImage.getHeight() == 40) {
													File[] iconFileList = { fileslist[ii] };
													// 上傳主檔圖片
													image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
															.asList(IMG_TYPE.ICON.getValue())), new ArrayList<String>(Arrays.asList(specMajor
															.getMainSpecId().toString())), new ArrayList<File>(Arrays.asList(iconFileList)), null,
															coverId);

													// 將原始主圖檔存一份起來
													sbMainPath.setLength(0);
													sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
													sbMainPath.append(aProposeProduct.getId().substring(0, 4));
													sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
															.append(tmpMianImg);
												} else {
													this.addActionError("商品 " + aProposeProduct.getId() + "，主规格示意图:" + fileslist[ii].getName()
															+ "尺寸应为40x40");
												}
											}
										}

									}
								}

							}
						}
					} else {
						/* 開始存說明檔圖片 */
						if (descMap.containsKey(uploadFileName[i].toLowerCase())) {// 判斷上傳的圖檔是否包含在Map裏
							if (descMap.get(uploadFileName[i].toLowerCase()).equals(aProposeProduct.getId())) {// 只有相同的ID才存入路徑及圖檔
								File[] descFileList = { upload[i] };
								// fis = new FileInputStream(upload[i]);
								// File f = new File(imgMfilePath.toString() + uploadFileName[i]);
								// InputStream inputStream = new FileInputStream(upload[i]);
								// OutputStream out = new FileOutputStream(f);
								// byte buf[] = new byte[1024];
								// int len;
								// while ((len = inputStream.read(buf)) > 0) {
								// out.write(buf, 0, len);
								// }
								// out.close();
								// inputStream.close();
								// BufferedImage bufferedImage = ImageIO.read(new File(imgMfilePath.toString()
								// + uploadFileName[i].toLowerCase()));
								// imageUtils = new ImageUtils();
								// String timeflag = String.valueOf(new Date().getTime());
								// if (uploadFileName[i].toLowerCase().endsWith("jpg") == true) {
								// subName = "jpg";
								// imageUtils.descResize(aProposeProduct.getId(), bufferedImage, "d" + timeflag, subName, imgMfilePath
								// .toString());
								// }
								// if (uploadFileName[i].toLowerCase().endsWith("gif") == true) {
								// subName = "gif";
								// imageUtils.descResize(aProposeProduct.getId(), bufferedImage, "d" + timeflag, subName, imgMfilePath
								// .toString());
								// }
								// image = new Image();
								// image.setImgFilePath(baseImgPath + "_d" + timeflag + "." + "jpg");
								// image.setProductId(aProposeProduct.getId());
								// image.setShowSeq(i + 1);
								// image.setType("DESC");
								// image.setIsDelete("N");
								// imageService.save(image);
								// // FileUtils.forceDelete(f);
								// // 将值放入map及list ex:key=newname.jpg value=oldname.jpg,0001
								// sbNameMapKey.setLength(0);
								// sbNameMapValue.setLength(0);
								// sbNameMapKey.append(aProposeProduct.getId()).append("_d").append(timeflag).append(".").append(subName);
								// sbNameMapValue.append(uploadFileName[i].toLowerCase()).append(",").append(aProposeProduct.getId());
								// replaceNameMap.put(sbNameMapKey.toString(), sbNameMapValue.toString());
								// replaceMapKeyList.add(sbNameMapKey.toString());
								//								
								File[] prdtFileList = { upload[i] };
								BufferedImage bufferedImage = ImageIO.read(upload[i]);
								if (bufferedImage.getWidth() <= 700) {
									image2Service.uploadImage(aProposeProduct.getId(), new ArrayList<String>(Arrays.asList(IMG_TYPE.DESC
											.getValue())), null, new ArrayList<File>(Arrays.asList(descFileList)), null);
								} else {
									this.addActionError("商品 " + aProposeProduct.getId() + "，说明图片:" + uploadFileName[i] + "宽度限700以内");
								}
							}
						}
						/* 開始存商品圖片 */
						if (prdtMap.containsKey(uploadFileName[i].toLowerCase())) {// 判斷上傳的圖檔是否包含在Map裏
							if (prdtMap.get(uploadFileName[i].toLowerCase()).equals(aProposeProduct.getId())) {// 只有相同的ID才存入路徑及圖檔
								File[] prdtFileList = { upload[i] };
								BufferedImage bufferedImage = ImageIO.read(upload[i]);
								if (bufferedImage.getWidth() == 520 && bufferedImage.getHeight() <= 620) {

									image2Service.uploadImage(aProposeProduct.getId(), new ArrayList<String>(Arrays.asList(IMG_TYPE.PRDT
											.getValue())), null, new ArrayList<File>(Arrays.asList(prdtFileList)), null);
								} else {
									this.addActionError("商品 " + aProposeProduct.getId() + "`,商品图片:" + uploadFileName[i] + "尺寸应为520x620");
								}

							}
						}

						// 需要主規格id的圖：主規格方形圖，主規格長形圖，方形規格細節圖，長形規格細節圖，主規格示意圖
						if (null != specMajors) {
							for (SpecificationMajor specMajor : specMajors) {
								List<ProposeSpecification> pss = proposeSpecificationService.getSpecificationByProductIdAndMainName(
										product.getProductId(), specMajor.getMainSpecName());

								if (pss.size() > 0) {
									ProposeSpecification ps = pss.get(0);
									String coverId = "";
									if ("Y".equals(ps.getIsCover())) {
										coverId = specMajor.getMainSpecId().toString();

									}
									String tmpMianImg = upload[i].getName();
									// 主規格方形圖
									if (null != ps.getProposeProductMainImg()) {
										if (ps.getProposeProductMainImg().toLowerCase().equals(uploadFileName[i].toLowerCase())) {
											BufferedImage bufferedImage = ImageIO.read(upload[i]);
											if (bufferedImage.getWidth() == 500 && bufferedImage.getHeight() == 500) {

												File[] mainFileList = { upload[i] };
												// 上傳主檔圖片
												image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
														.asList(IMG_TYPE.MAIN.getValue())), new ArrayList<String>(Arrays.asList(specMajor
														.getMainSpecId().toString())), new ArrayList<File>(Arrays.asList(mainFileList)), null);

												// 將原始主圖檔存一份起來
												sbMainPath.setLength(0);
												sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
												sbMainPath.append(aProposeProduct.getId().substring(0, 4));
												sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
														.append(uploadFileName[i]);
												FileUtils.copyFile(upload[i], new File(sbMainPath.toString()));
											} else {
												this.addActionError("商品 " + aProposeProduct.getId() + "，主规格方形图:" + uploadFileName[i]
														+ "尺寸应为500x500");
											}
										}
									}
									// 主規格長形圖
									if (null != ps.getProposeProductRMainImg()) {
										if (ps.getProposeProductRMainImg().toLowerCase().equals(uploadFileName[i].toLowerCase())) {
											BufferedImage bufferedImage = ImageIO.read(upload[i]);
											if (bufferedImage.getWidth() == 400 && bufferedImage.getHeight() == 530) {
												File[] rmainFileList = { upload[i] };
												// 上傳主檔圖片
												image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
														.asList(IMG_TYPE.RMAIN.getValue())), new ArrayList<String>(Arrays.asList(specMajor
														.getMainSpecId().toString())), new ArrayList<File>(Arrays.asList(rmainFileList)), null);

												// 將原始主圖檔存一份起來
												sbMainPath.setLength(0);
												sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
												sbMainPath.append(aProposeProduct.getId().substring(0, 4));
												sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
														.append(tmpMianImg);
											} else {
												this.addActionError("商品 " + aProposeProduct.getId() + "，主规格长型图:" + uploadFileName[i]
														+ "尺寸应为400x530");
											}
										}
									}
									// 規格細節圖，圖檔類型由"商品页为长形图/正方图?"來決定
									String mainPicType = "S".equals(aProposeProduct.getGraphicType()) ? IMG_TYPE.MAIN.getValue()
											: IMG_TYPE.RMAIN.getValue();
									if (null != ps.getProposeProductMainSpecPic()) {
										if (ps.getProposeProductMainSpecPic().toLowerCase().equals(uploadFileName[i].toLowerCase())) {
											BufferedImage bufferedImage = ImageIO.read(upload[i]);
											if (("S".equals(aProposeProduct.getGraphicType()) && bufferedImage.getWidth() == 400 && bufferedImage
													.getHeight() == 400)
													|| ("R".equals(aProposeProduct.getGraphicType()) && bufferedImage.getWidth() == 400 && bufferedImage
															.getHeight() == 530)) {
												File[] mainFileList = { upload[i] };
												// 上傳主檔圖片
												image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
														.asList(mainPicType)), new ArrayList<String>(Arrays.asList(specMajor.getMainSpecId()
														.toString())), new ArrayList<File>(Arrays.asList(mainFileList)), null);

												// 將原始主圖檔存一份起來
												sbMainPath.setLength(0);
												sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
												sbMainPath.append(aProposeProduct.getId().substring(0, 4));
												sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
														.append(uploadFileName[i]);
												FileUtils.copyFile(upload[i], new File(sbMainPath.toString()));

											} else {
												this.addActionError("商品 " + aProposeProduct.getId() + "，规格细节图:" + uploadFileName[i]
														+ "尺寸相同于主图尺寸");
											}

										}
									}

									// 主規格示意圖
									if (null != ps.getProposeProductIconPic()) {
										if (ps.getProposeProductIconPic().toLowerCase().equals(uploadFileName[i].toLowerCase())) {
											BufferedImage bufferedImage = ImageIO.read(upload[i]);
											if (bufferedImage.getWidth() == 40 && bufferedImage.getHeight() == 40) {
												File[] iconFileList = { upload[i] };
												// 上傳主檔圖片
												image2Service.uploadImage(specMajor.getProductId(), new ArrayList<String>(Arrays
														.asList(IMG_TYPE.ICON.getValue())), new ArrayList<String>(Arrays.asList(specMajor
														.getMainSpecId().toString())), new ArrayList<File>(Arrays.asList(iconFileList)), null,
														coverId);

												// 將原始主圖檔存一份起來
												sbMainPath.setLength(0);
												sbMainPath.append(ServerValue.getMidApachePath()).append("PImg").append(File.separator);
												sbMainPath.append(aProposeProduct.getId().substring(0, 4));
												sbMainPath.append(File.separator).append(aProposeProduct.getId()).append(File.separator)
														.append(tmpMianImg);
											} else {
												this.addActionError("商品 " + aProposeProduct.getId() + "，主规格示意图:" + uploadFileName[i]
														+ "尺寸应为40x40");
											}
										}
									}

								}
							}

						}

					}
				}
				// 開始置換HTML的圖檔名稱
				proposeProductService.replaceImageName(replaceNameMap, replaceMapKeyList);
				crit = new CommonCriteria();
				if ("N".equalsIgnoreCase(flag)) {
					crit.addEq("proposeProductBatchId", enterPrdctBatchId);
				} else {
					crit.addEq("proposeProductBatchId", prpsPrdctBatchId);
				}
				proposeProducts = proposeProductService.getList(0, -1, crit, null);
				product.setStepFlag(4);
				product2Service.save(product);
			}
			File fileDel = new File(ServerValue.getMidApachePath() + File.separator + "PImg" + File.separator);
			File[] files = fileDel.listFiles(new FilenameFilter() {

				public boolean accept(File dir, String name) {
					return name.length() != 4
							&& ("logo_ok_b.png,blank_75.gif,blank_500.gif,blank_50.gif,blank_250.gif,blank_135.gif,blank_100.gif,tmpZip,blank_r93.gif,blank_r130.gif,blank_r180.gif,blank_r330.gif,blank_r225.gif,blank_r530.gif,40x40.gif,blank_225.gif,blank_r99.gif"
									.indexOf(name) == -1);
				}
			});
			if (null != files) {
				for (int i = 0; i < files.length; i++) {
					FileUtils.forceDelete(files[i]);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			logger.info("processUploadImg Error: " + e.toString());
		}
		return "uploadImg";
	}

	public void setBrief(String brief) {
		this.brief = brief;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public void setDetails(String details) {
		this.details = details;
	}

	/**
	 * @param enterPrdctBatchId the enterPrdctBatchId to set
	 */
	public void setEnterPrdctBatchId(String enterPrdctBatchId) {
		this.enterPrdctBatchId = enterPrdctBatchId;
	}

	/**
	 * @param flag the flag to set
	 */
	public void setFlag(String flag) {
		this.flag = flag;
	}

	/**
	 * @param image the image to set
	 */
	public void setImage(Image image) {
		this.image = image;
	}

	/**
	 * @param imageService the imageService to set
	 */
	// public void setImageService(Image2Service imageService) {
	// this.imageService = imageService;
	// }

	public void setImgMfilePath(StringBuffer imgMfilePath) {
		this.imgMfilePath = imgMfilePath;
	}

	/**
	 * @param proposeProduct the proposeProduct to set
	 */
	public void setProposeProduct(ProposeProduct proposeProduct) {
		this.proposeProduct = proposeProduct;
	}

	/**
	 * @param proposeProducts the proposeProducts to set
	 */
	public void setProposeProducts(List<ProposeProduct> proposeProducts) {
		this.proposeProducts = proposeProducts;
	}

	/**
	 * @param proposeProductService the proposeProductService to set
	 */
	public void setProposeProductService(ProposeProductService proposeProductService) {
		this.proposeProductService = proposeProductService;
	}

	/**
	 * @param prpsPrdctBatchId the prpsPrdctBatchId to set
	 */
	public void setPrpsPrdctBatchId(String prpsPrdctBatchId) {
		this.prpsPrdctBatchId = prpsPrdctBatchId;
	}

	/**
	 * @param upload the upload to set
	 */
	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	/**
	 * @param uploadFileName the uploadFileName to set
	 */
	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	/* 上傳商品圖 */
	public String uploadImg() throws CoreException {
		proposeProducts = null;
		if (flag.equalsIgnoreCase("N")) {
			prpsPrdctBatchId = "";
		}
		return "uploadImg";
	}

}
